package com.exm.collectcodenew.juc.interrupted;

/**
 * 在触发InterruptedException异常的同时，JVM会同时把线程的中断标志位清除，所以，这个时
 * 候在run()方法中判断的currentThread.isInterrupted()会返回false，也就不会退出当前while循环了。
 */
public class InterruptedTask implements Runnable{
    @Override
    public void run() {
        Thread currentThread = Thread.currentThread();
        while (true){
            if(currentThread.isInterrupted()){
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                //在触发InterruptedException异常的同时，JVM会同时把线程的中断标志位清除，捕获异常之后需重新设置中断标志位，如果不设置就跳不出while(true)循环
//                currentThread.interrupt();
            }
        }
    }

    public static void main(String[] args) {
        InterruptedTask interruptedTask = new InterruptedTask();
        Thread interruptedThread = new Thread(interruptedTask);
        interruptedThread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptedThread.interrupt();
    }
}
